<template>
  <div class="card">
    <el-button type="primary" :icon="CirclePlus" @click="add">新增用户</el-button>

    <div style="margin-top: 20px">
      <el-table
        :data="tableData"
        style="width: 100%"
        border
        stripe
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="nickname" label="昵称" />
        <el-table-column prop="role" label="角色">
          <template #default="{ row }">
            <el-tag v-for="(item, index) in row.role" :key="index">{{ item }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="register_date" label="注册时间">
          <template #default="{ row }">{{ timeFormate(row.register_date) }}</template>
        </el-table-column>
        <el-table-column prop="last_login_date" label="最后登录时间">
          <template #default="{ row }">
            {{ timeFormate(row.last_login_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="last_login_ip" label="最后登录IP" />

        <el-table-column label="操作" width="180px" fixed="right" align="center">
          <template #default="{ row }">
            <el-button size="small" type="warning" :icon="EditPen" @click="edit(row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" :icon="Delete" @click="remove(row)">
              删除
            </el-button>
          </template>
        </el-table-column>

        <template #empty>
          <el-empty description="暂无数据" />
        </template>
      </el-table>
    </div>

    <div style="margin-top: 20px; display: flex; justify-content: center">
      <el-pagination
        background
        @current-change="handleCurrentChange"
        :current-page="pageParams.pageNum"
        :page-size="pageParams.pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
      />
    </div>

    <UserDialog
      v-model:visible="dialogVisible"
      :type="dialogType"
      :userData="currentUser"
      @success="handleDialogSuccess"
      @cancel="handleDialogCancel"
    />
  </div>
</template>

<script setup lang="ts" name="accountManage">
import { onMounted, reactive, ref } from 'vue'
import { CirclePlus, Delete, EditPen, Setting } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import { deleteUserApi, getUserListApi } from '@/api/modules/user'
import { timeFormate } from '@/utils/timeFormat'
import { UserApi } from '@/api/interface/user'
import UserDialog from './components/UserDialog.vue'

const tableData = ref<UserApi.UniCloudUser[]>([])
const pageParams = reactive({
  pageNum: 1,
  pageSize: 10
})
const total = ref(0)
const loading = ref(false)

// 弹窗相关
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const currentUser = ref({})

const handleCurrentChange = (page) => {
  pageParams.pageNum = page
  getList() // 切换页码时重新获取数据
}

const add = () => {
  dialogType.value = 'add'
  currentUser.value = {}
  dialogVisible.value = true
}

const edit = (row) => {
  dialogType.value = 'edit'
  currentUser.value = { ...row }
  dialogVisible.value = true
}

const remove = (row) => {
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let res = await deleteUserApi({ params: { uid: row._id } })
      if (res.errCode === 0) {
        ElMessage.success('删除成功')
        getList()
      }
    })
    .catch(() => {})
}

// 弹窗确认回调
const handleDialogSuccess = () => {
  getList()
}

// 弹窗取消回调
const handleDialogCancel = () => {
  dialogVisible.value = false
}

const getList = () => {
  loading.value = true
  getUserListApi({ params: pageParams })
    .then((res) => {
      if (res.errCode === 0) {
        tableData.value = res.data
        total.value = res.count as number
      }
    })
    .catch((err) => {
      console.error('获取用户列表失败', err)
    })
    .finally(() => {
      loading.value = false
    })
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.card {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}
</style>
